package com.gh.deskTopSearch.file.fetch.support;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import com.gh.deskTopSearch.file.fetch.Chooser;

/**
 * 将选择器分成组，一个组内的选择器内部，同时拥有它们各自的关系.
 * 
 * @author rjgc
 * 
 */
public class ChooserGroup implements Chooser {

	private List<ChooserClause> clauses = new LinkedList<ChooserClause>();

	public ChooserGroup() {
	}

	public ChooserGroup(List<ChooserClause> clauses) {
		this.clauses.addAll(clauses);
	}

	public ChooserGroup(ChooserClause clause, ChooserClause... clauses) {
		this.clauses.add(clause);
		this.clauses.addAll(Arrays.asList(clauses));
	}

	public void add(ChooserClause clause) {
		clauses.add(clause);
	}

	@Override
	public boolean accept(File file) {
		boolean flag = false;
		for (ChooserClause clause : clauses) {
			boolean isAccepted = clause.getChooser().accept(file);
			if (clause.getOccur() == ChooserClause.Occur.SHOULD) {
				if (isAccepted) {
					// 如果 或为真，则必为真
					return true;
				}
				// 且 和 非， 都是快速失败的，只要有一个是假，则立即返回 false,如果为真，则置flag 为 真
			} else if (clause.getOccur() == ChooserClause.Occur.MUST) {
				if (!isAccepted) {
					return false;
				} else {
					flag = true;
				}
			} else if (clause.getOccur() == ChooserClause.Occur.NOT) {
				isAccepted = !isAccepted;
				if (!isAccepted) {
					return false;
				} else {
					flag = true;
				}
			}
		}
		return flag;
	}

}
